﻿using EmployeeLeaveSystem.Shared.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace EmployeeLeaveSystem.Server.Controllers.AuthController {
    [Route("api/Auth/[Action]")]
    [ApiController]
    public class AuthController : ControllerBase {
        readonly EpMainContext _mainContext;
        public AuthController(EpMainContext mainContext) { _mainContext = mainContext; }
        public ActionResult<StaffInfo?> GetUsrInfoById(int id) {
            return _mainContext.StaffInfos.Where(x => x.Id == id).Include(x => x.Department).FirstOrDefault();
        }
        [HttpPost]
        public ActionResult UpdateUsrInfo(StaffInfo? staffInfo) {
            if (staffInfo == null) {
                return BadRequest();
            } else {
                staffInfo.UpperStaff = null;
                staffInfo.childStaffs = new();
                _mainContext.StaffInfos.Update(staffInfo);
                _mainContext.SaveChanges();
                return Ok();
            }
        }
        [HttpGet]
        public ActionResult<List<StaffInfo>> GetAllUsrInfos() {
            return _mainContext.StaffInfos.ToList();
        }
        [HttpGet]
        public void DeleteUsr(int id) {
            _mainContext.StaffInfos.Remove(new StaffInfo() { Id = id });
            _mainContext.SaveChanges();
        }
        [HttpPost]
        public void AddAuth(StaffInfo staffInfo) {
            _mainContext.StaffInfos.Add(staffInfo);
            _mainContext.SaveChanges();
        }
        [HttpGet]
        public List<Department> GetAllDepartments() {
            return _mainContext.Departments.ToList();
        }
        [HttpPost]
        public void AddDepartment(Department department) {
            _mainContext.Departments.Add(department);
            _mainContext.SaveChanges();
        }
        [HttpPost]
        public void UpdateDepartment(Department department) {
            _mainContext.Departments.Update(department);
            _mainContext.SaveChanges();
        }
        [HttpGet]
        public void DeleteDepartment(int id) {
            _mainContext.Departments.Remove(new Department() { Id = id });
            _mainContext.SaveChanges();
        }
        // 获得Staff为Id的所有属下信息
        [HttpGet]
        public List<StaffInfo> GetAllChilden(int id) {
            return _mainContext.StaffInfos.Where(x => x.UpperStaffId == id).ToList();
        }
    }
}
